package com.cirkana.viewer.qr;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

import com.cirkana.CirkanaActivity;
import com.cirkana.viewer.R;
import com.cirkana.viewer.qr.model.QRController;
import com.cirkana.viewer.qr.model.QRException;

public class QRReaderActivity extends CirkanaActivity {

	private static final int CAMERA_PIC_REQUEST = 1;

	private ImageView qrImageView;
	private EditText qrTextEditText;
	private Button againButton;
	private Button okButton;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.qrreader);

		this.qrImageView = (ImageView) findViewById(R.id.qrreader_qrimage);
		this.qrTextEditText = (EditText) findViewById(R.id.qrreader_qrtext);
		this.againButton = (Button) findViewById(R.id.qrreader_again);
		this.okButton = (Button) findViewById(R.id.qrreader_ok);

		launchCamera();
		
		this.againButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				launchCamera();
			}
		});
		
		this.okButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
	}

	private void launchCamera() {
		Intent cameraIntent = new Intent(
				android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
		startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == CAMERA_PIC_REQUEST) {
			if (resultCode == RESULT_OK) {
				Bitmap qrImage = (Bitmap) data.getExtras().get("data");
				qrImageView.setImageBitmap(qrImage);
				try {
					qrTextEditText.setText(QRController.decodeQR(qrImage));
				} catch (QRException e) {
					showErrorMessage(e);
				}
				// TODO: Caught picture must be deleted.
			}
		}
	}

}
